#!/usr/bin/env python3
r"""
Split sections/04_appendices.tex into multiple files based on \section markers.

Usage:
    python split_appendices.py
"""

import os
import re

def find_section_line(lines, section_marker):
    """Find the line number where a section starts."""
    for i, line in enumerate(lines):
        if section_marker in line:
            return i
    return -1

def extract_lines_by_range(lines, start_line, end_line):
    """Extract lines from start_line (inclusive) to end_line (exclusive)."""
    if end_line == -1:
        return lines[start_line:]
    return lines[start_line:end_line]

def split_appendices():
    """Split the appendices file into separate files."""

    # Read the original file
    appendices_file = 'sections/04_appendices.tex'

    print(f"Reading {appendices_file}...")
    with open(appendices_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    print(f"Total lines: {len(lines)}")

    # Create appendices subdirectory
    appendices_dir = 'sections/appendices'
    os.makedirs(appendices_dir, exist_ok=True)
    print(f"Created directory: {appendices_dir}")

    # Define section markers and their corresponding output files
    sections = [
        {
            'marker': '\\section{谱稳定性定理的证明}',
            'file': 'appendix_a_spectral_proof.tex',
            'start_line': None,
            'end_line': None
        },
        {
            'marker': '\\section{主方程良定性与概率守恒}',
            'file': 'appendix_b_master_equation.tex',
            'start_line': None,
            'end_line': None
        },
        {
            'marker': '\\section{信息-热力学对偶性的证明}',
            'file': 'appendix_c_info_thermo.tex',
            'start_line': None,
            'end_line': None
        },
        {
            'marker': '\\section{热力学转移与方差动力学的详细推导}',
            'file': 'appendix_d_thermodynamics.tex',
            'start_line': None,
            'end_line': None
        },
        {
            'marker': '\\section{普适类的重正化群推导}',
            'file': 'appendix_e_rg_universality.tex',
            'start_line': None,
            'end_line': None
        },
        {
            'marker': '\\section*{致谢}',
            'file': 'acknowledgements.tex',
            'start_line': None,
            'end_line': None
        }
    ]

    # Find line numbers for each section (first pass: find start lines)
    print("\nFinding section start lines...")
    for section in sections:
        section['start_line'] = find_section_line(lines, section['marker'])
        if section['start_line'] == -1:
            print(f"ERROR: Could not find section: {section['marker']}")
            return
        print(f"  {section['file']}: starts at line {section['start_line']}")

    # Second pass: set end lines
    print("\nSetting section boundaries...")
    for i, section in enumerate(sections):
        # End line is the start of the next section (or end of file for last section)
        if i < len(sections) - 1:
            section['end_line'] = sections[i + 1]['start_line']
        else:
            section['end_line'] = len(lines)

        line_count = section['end_line'] - section['start_line']
        print(f"  {section['file']}: lines {section['start_line']}-{section['end_line']} ({line_count} lines)")

    # Extract header (everything before first section)
    header_end = sections[0]['start_line']
    header_lines = lines[:header_end]

    print(f"\nHeader lines (0-{header_end}): {len(header_lines)} lines")

    # Write each section to its own file
    print("\nWriting section files...")
    for section in sections:
        output_path = os.path.join(appendices_dir, section['file'])
        content_lines = extract_lines_by_range(lines, section['start_line'], section['end_line'])

        with open(output_path, 'w', encoding='utf-8') as f:
            f.writelines(content_lines)

        print(f"  Created {output_path} ({len(content_lines)} lines)")

    # Create new main appendices file that includes all the split files
    print("\nCreating new main appendices file...")
    new_appendices_content = []

    # Add header
    new_appendices_content.extend(header_lines)

    # Add \input commands for each section
    for section in sections:
        new_appendices_content.append(f"\\input{{sections/appendices/{section['file'].replace('.tex', '')}}}\n")
        new_appendices_content.append("\n")

    # Backup original file
    backup_file = appendices_file + '.backup'
    print(f"Backing up original to {backup_file}...")
    with open(backup_file, 'w', encoding='utf-8') as f:
        f.writelines(lines)

    # Write new main file
    print(f"Writing new {appendices_file}...")
    with open(appendices_file, 'w', encoding='utf-8') as f:
        f.writelines(new_appendices_content)

    print(f"New {appendices_file}: {len(new_appendices_content)} lines")

    # Summary
    print("\n" + "="*60)
    print("SUMMARY")
    print("="*60)
    print(f"Original file: {appendices_file} ({len(lines)} lines)")
    print(f"Backup saved to: {backup_file}")
    print(f"New main file: {appendices_file} ({len(new_appendices_content)} lines)")
    print(f"\nSplit into {len(sections)} files in {appendices_dir}:")
    for section in sections:
        print(f"  - {section['file']}")
    print("\nTo compile, use the same command as before:")
    print("  cd chinese_translation")
    print("  xelatex hierarchical_cooperation_paper_chinese.tex")
    print("  biber hierarchical_cooperation_paper_chinese")
    print("  xelatex hierarchical_cooperation_paper_chinese.tex")
    print("  xelatex hierarchical_cooperation_paper_chinese.tex")

if __name__ == '__main__':
    # Change to the chinese_translation directory
    script_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(script_dir)

    split_appendices()
    print("\n✅ Appendices split successfully!")
